package com.maltys.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @author malty
 * @link <a href="https://leetcode.cn/problems/combination-sum-iii/">组合总数3</a>
 */
public class CombinationsSumIII {
    public static void main(String[] args) {
        CombinationsSumIII combinations3 = new CombinationsSumIII();
        List<List<Integer>> lists = combinations3.combinationSum3(3, 9);
        lists.forEach(System.out::println);
    }

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        backTracing(n, k, 0, 1, new ArrayList<>(), res);
        return res;
    }

    public void backTracing(int target, int k, int sum, int idx, List<Integer> list, List<List<Integer>> res) {
        if (list.size() == k && target == sum) {
            res.add(new ArrayList<>(list));
            return;
        }

        if (sum > target || list.size() > k) {
            return;
        }

        for (int i = idx; i < 10; i++) {
            if(sum + i > target){
                continue;
            }
            list.add(i);
            backTracing(target, k, sum + i, i + 1, list, res);
            list.remove(list.size() - 1);
        }
    }
}
